package use.thread.sync;

import sun.plugin2.util.SystemUtil;

import java.util.concurrent.*;

public class ForkJoinExample extends RecursiveTask<Integer> {
    private final int threadHold = 5;
    private int first;
    private int last;

    public ForkJoinExample(int first, int last) {
        this.first = first;
        this.last = last;
    }
    @Override
    protected Integer compute() {
        int result = 0;
        if (last - first <= threadHold) {
            for (int i = first; i <= last; i++) {
                result += i;
            }
        } else {
            int middle = (first + last) / 2;
            ForkJoinExample leftTask = new ForkJoinExample(first, middle);
            ForkJoinExample rightTask = new ForkJoinExample(middle + 1, last);
            leftTask.fork();
            rightTask.fork();
            result = leftTask.join() + rightTask.join();
        }
        return result;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinExample example = new ForkJoinExample(1, 1000000);
//        ForkJoinPool forkJoinPool = new ForkJoinPool();
//        Future result = forkJoinPool.submit(example);
//        System.out.println(result.get());
        example.computer();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    public int computer() {
        int aa = 0;
        for (int i = 0; i <=1000000; i++) {
            aa += i;
        }
        System.out.println("---" + aa);
        return aa;
    }
}
